package com.evaluation_system.handler;

import com.evaluation_system.constant.MessageConstant;
import com.evaluation_system.exception.BaseException;
import com.evaluation_system.pojo.Result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // ✅ 捕获自定义业务异常（含密码错误、账号错误等）
    @ExceptionHandler(BaseException.class)
    public ResponseEntity<Result<?>> handleBaseException(BaseException ex) {
        log.error("业务异常：{}", ex.getMessage());
        return ResponseEntity
                .badRequest()
                .contentType(MediaType.valueOf("application/json;charset=UTF-8"))
                .body(Result.error(ex.getMessage()));
    }

    // ✅ 捕获 SQL 唯一约束异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResponseEntity<Result<?>> handleSqlException(SQLIntegrityConstraintViolationException ex) {
        log.error("数据库异常：{}", ex.getMessage());
        String message = ex.getMessage();
        String msg = MessageConstant.UNKNOWN_ERROR;

        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            msg = username + MessageConstant.ALREADY_EXISTS;
        }

        return ResponseEntity
                .badRequest()
                .contentType(MediaType.valueOf("application/json;charset=UTF-8"))
                .body(Result.error(msg));
    }
}